<template>
  <div class="header-wrapper">
    <div class="main-header">
      <div class="nav-container">
        <router-link to="/" class="logo">
          <div class="logo-icon">
            <i class="fas fa-hospital"></i>
          </div>
          <div>
            <div class="logo-text">安心医疗</div>
            <div class="logo-tagline">值得信赖的医疗服务平台</div>
          </div>
        </router-link>

        <!-- 桌面导航 -->
        <nav class="nav-menu">
          <router-link v-for="route in routes" :key="route.name" :to="route.path" class="nav-link"
            :class="{ active: isActive(route.path) }">
            {{ route.name }}
          </router-link>
        </nav>

        <div class="nav-actions">
          <el-popover v-if="appStore.user.isLoggedIn" placement="bottom" width="180" trigger="hover">
            <template #reference>
              <button class="btn btn-outline user-btn">
                <i class="fas fa-user"></i>
                {{ appStore.user.name }}
              </button>
            </template>
            <div class="popover-content">
              <div class="popover-item">用户名：{{ appStore.user.name }}</div>
              <div class="popover-item clickable" @click="goToProfile">个人设置</div>
              <div class="popover-item clickable" @click="goToRecords">就诊病历</div>
              <div class="popover-item clickable" @click="goToMyAppointments">预约信息</div>
              <el-button type="danger" size="small" @click="appStore.logout()">退出登录</el-button>
            </div>
          </el-popover>
          <button v-else class="btn btn-outline" @click="toggleLoginModal">
            <i class="fas fa-user"></i>
            登录/注册
          </button>
        </div>
      </div>
    </div>

    <!-- 登录/注册模态框 -->
    <div v-if="showLoginModal" class="login-modal">
      <div class="modal-content">
        <div class="custom-tab-header">
          <div :class="['tab-item', { active: activeTab === 'login' }]" @click="switchTab('login')">登录</div>
          <div :class="['tab-item', { active: activeTab === 'register' }]" @click="switchTab('register')">注册</div>
          <div class="tab-slider" :style="{ left: activeTab === 'login' ? '0%' : '50%' }"></div>
        </div>
        <div v-if="activeTab === 'login'">
          <h3>用户登录</h3>
          <div class="form-group">
            <label for="username">用户名：</label>
            <input type="text" id="username" v-model="username" />
          </div>
          <div class="form-group">
            <label for="password">密码：</label>
            <input type="password" id="password" v-model="password" />
          </div>
          <button class="btn btn-primary" @click="handleLogin">登录</button>
          <div class="forgot-link" @click="ElMessage.info('请联系管理员重置密码')">忘记密码？</div>
        </div>
        <div v-else>
          <h3>用户注册</h3>
          <div class="form-group">
            <label for="regUsername">用户名：</label>
            <input type="text" id="regUsername" v-model="regUsername" />
          </div>
          <div class="form-group">
            <label for="regPassword">密码：</label>
            <input type="password" id="regPassword" v-model="regPassword" />
          </div>
          <div class="form-group">
            <label for="realName">姓名：</label>
            <input type="text" id="realName" v-model="realName" />
          </div>
          <div class="form-group">
            <label for="regPhone">手机号：</label>
            <input type="text" id="regPhone" v-model="regPhone" />
          </div>
          <!-- <div class="form-group">
            <label for="regEmail">邮箱：</label>
            <input type="text" id="regEmail" v-model="regEmail" />
          </div> -->
          <button class="btn btn-primary" @click="handleRegister">注册</button>
        </div>
        <button class="close-btn" @click="showLoginModal = false">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useAppStore } from '../stores/appStore'
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { loginApi, registerApi } from '../api/user'

// 路由配置
const routes = [
  { name: '首页', path: '/' },
  { name: '预约挂号', path: '/appointment' },
  { name: 'AI导诊', path: '/aiDoctor' },
  { name: '就诊指南', path: '/guide' },
  { name: '健康资讯', path: '/news' }
]

// 使用Pinia状态
const appStore = useAppStore()

// 登录表单状态
const username = ref('')
const password = ref('')
const showLoginModal = ref(false)

// 注册表单状态
const regUsername = ref('')
const regPassword = ref('')
const realName = ref('')
const regPhone = ref('')
const regEmail = ref('')

// 路由钩子
const router = useRouter()
const route = useRoute()

// 检查当前路由是否激活
const isActive = (path: string) => {
  return route.path === path
}

// 切换登录/注册tab
const activeTab = ref<'login' | 'register'>('login')

// 切换登录模态框
const toggleLoginModal = () => {
  if (appStore.user.isLoggedIn) {
    appStore.logout()
  } else {
    showLoginModal.value = true
  }
}

// 切换登录/注册tab
const switchTab = (tab: 'login' | 'register') => {
  activeTab.value = tab
}

// 处理登录
const handleLogin = async () => {
  if (!username.value || !password.value) {
    ElMessage.warning('请输入用户名和密码')
    return
  }
  try {
    const data = await loginApi(username.value, password.value) as any
    if (data.code === 200) {
      const token = data.data
      appStore.login(username.value, token)
      localStorage.setItem('token', token)
      ElMessage.success('登录成功')
      showLoginModal.value = false
      username.value = ''
      password.value = ''
    } else {
      ElMessage.error(data.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请稍后重试')
  }
}

// 注册处理
const handleRegister = async () => {
  if (!regUsername.value || !regPassword.value) {
    ElMessage.warning('请输入用户名和密码')
    return
  }
  try {
    const res = await registerApi({
      username: regUsername.value,
      password: regPassword.value,
      realName: realName.value,
      phone: regPhone.value,
      // email: regEmail.value
    }) as any
    if (res.code === 200) {
      ElMessage.success('注册成功，请登录')
      switchTab('login')
      // 清空注册表单
      regUsername.value = ''
      regPassword.value = ''
      realName.value = ''
      regPhone.value = ''
      // regEmail.value = ''
    } else {
      ElMessage.error(res.msg || '注册失败')
    }
  } catch (error) {
    ElMessage.error('注册失败，请稍后重试')
  }
}

const goToProfile = () => router.push('/profile')
const goToRecords = () => router.push('/records')
const goToMyAppointments = () => router.push('/appointments')

onMounted(() => {
  window.addEventListener('show-login-modal', () => {
    showLoginModal.value = true
    activeTab.value = 'login'
  })
})
onUnmounted(() => {
  window.removeEventListener('show-login-modal', () => { })
})
</script>

<style scoped lang="scss">
.main-header {
  background: var(--white);
  box-shadow: var(--shadow-sm);
  padding: 0 8%;
  position: sticky;
  top: 0;
  z-index: 1000;

  .nav-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 0;
  }

  .logo {
    display: flex;
    align-items: center;
    gap: 15px;
    text-decoration: none;

    .logo-icon {
      width: 50px;
      height: 50px;
      background: var(--gradient-blue);
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: var(--white);
      font-size: 24px;
    }

    .logo-text {
      font-family: 'Poppins', sans-serif;
      font-weight: 700;
      font-size: 24px;
      color: var(--primary-blue);
    }

    .logo-tagline {
      font-size: 12px;
      color: var(--text-light);
      margin-top: 2px;
      letter-spacing: 1px;
    }
  }

  .nav-menu {
    display: flex;
    gap: 30px;

    .nav-link {
      color: var(--text-dark);
      text-decoration: none;
      font-weight: 500;
      padding: 8px 0;
      position: relative;
      transition: var(--transition);

      &::after {
        content: '';
        position: absolute;
        width: 0;
        height: 2px;
        bottom: 0;
        left: 0;
        background: var(--primary-blue);
        transition: var(--transition);
      }

      &:hover::after,
      &.active::after {
        width: 100%;
      }

      &:hover,
      &.active {
        color: var(--primary-blue);
      }
    }
  }

  .nav-actions {
    display: flex;
    gap: 15px;
    align-items: center;
  }

  .btn {
    padding: 10px 22px;
    border-radius: 50px;
    font-weight: 500;
    cursor: pointer;
    transition: var(--transition);
    border: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    box-shadow: var(--shadow-sm);

    &:hover {
      transform: translateY(-3px);
      box-shadow: var(--shadow);
    }
  }

  .btn-primary {
    background: var(--gradient-blue);
    color: var(--white);
  }

  .btn-outline {
    background: transparent;
    color: var(--primary-blue);
    border: 1px solid var(--primary-blue);
  }
}

.login-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;

  .modal-content {
    background: var(--white);
    padding: 30px;
    border-radius: 20px;
    width: 400px;
    position: relative;

    h3 {
      margin-bottom: 20px;
      color: var(--text-dark);
    }

    .close-btn {
      position: absolute;
      top: 15px;
      right: 15px;
      background: transparent;
      border: none;
      color: var(--text-light);
      cursor: pointer;

      &:hover {
        color: var(--text-dark);
      }
    }

    .form-group {
      margin-bottom: 15px;

      label {
        display: block;
        margin-bottom: 5px;
        color: var(--text-medium);
      }

      input {
        width: 100%;
        padding: 10px;
        border: 1px solid var(--medium-gray);
        border-radius: 8px;
        transition: var(--transition);

        &:focus {
          outline: none;
          border-color: var(--primary-blue);
          box-shadow: 0 0 0 2px rgba(13, 110, 253, 0.2);
        }
      }
    }

    .btn {
      width: 100%;
      justify-content: center;
      margin-top: 10px;
    }
  }
}

.custom-tab-header {
  display: flex;
  position: relative;
  background: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 24px;
  height: 40px;
  align-items: center;

  .tab-item {
    flex: 1;
    text-align: center;
    line-height: 40px;
    font-weight: 600;
    font-size: 16px;
    color: #888;
    cursor: pointer;
    z-index: 2;
    transition: color 0.2s;

    &.active {
      color: #1976d2;
    }
  }

  .tab-slider {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 50%;
    height: 4px;
    background: linear-gradient(90deg, #1976d2 0%, #21c8f6 100%);
    border-radius: 2px;
    transition: left 0.3s;
    z-index: 1;
  }
}

.forgot-link {
  margin-top: 12px;
  color: #1976d2;
  cursor: pointer;
  text-align: right;
  font-size: 14px;

  &:hover {
    text-decoration: underline;
  }
}

.user-btn {
  background: transparent;
  border: none;
  color: var(--primary-blue);
  font-weight: 600;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 8px;
}

.popover-content {
  font-size: 14px;
  color: #333;
  line-height: 1.8;
  text-align: center;

  .popover-item {
    padding: 6px 0;
    border-radius: 4px;
    transition: background 0.2s;

    &.clickable {
      cursor: pointer;
      color: #1976d2;

      &:hover {
        background: #f0f7ff;
        text-decoration: none;
      }
    }
  }

  .el-button {
    margin-top: 8px;
    width: 100%;
  }
}

@media (max-width: 992px) {
  .nav-menu {
    display: none !important;
  }
}
</style>
